<?php
include_once 'paomeBase.class.php';

/**
 * 大厅相关
 */
class centerModel extends paomeBaseModel
{

    public function __construct(& $base)
    {
        parent::__construct($base);

        $this->table = 'r_pm_users_rounds';
    }

    /*
     * 个人中心--获取用户跑步数据
     */
    public function getUserData($uid, $date){
        $season = $this->base->load('paome/paomeHall')->getCurrentSeason();
        $data = array();
        if(!empty($season)){
            $seasonId = $season['id'];
            $round = $this->base->load('paome/paomeHall')->getCurrentRound();      
            if(!empty($round)){
                $sql = "SELECT * FROM r_pm_users_rounds r WHERE uid = {$uid} AND r.type = {$round} AND r.contest_id = {$seasonId}";
                if(!empty($date)){
                    $sql .= " AND r.date = \"{$date}\"";
                }
                $sql .= " ORDER BY r.date DESC";
                $data = $this->paomeDb->getRow($sql);
                if($data){
                    $data['speed'] = common::sec3format($data['speed']);
                }
            }
        }               
        return $data;
    }

    /*
     * 个人中心--获取俱乐部数据
     */
    public function getClubData($clubId){
        $season = $this->base->load('paome/paomeHall')->getCurrentSeason();
        $data = array();
        if(!empty($season)){
            $seasonId = $season['id'];
            $round = $this->base->load('paome/paomeHall')->getCurrentRound(); 
            if(!empty($round)){
                $sql = "SELECT * FROM r_pm_club_rounds r WHERE club_id = {$clubId} AND r.type = {$round} AND contest_id = {$seasonId}";
                $data = $this->paomeDb->getRow($sql);
                if($data){
                    $data['speed'] = common::sec3format($data['speed']);
                }
            }
        }       
        return $data;
    }

    /*
     * 个人中心--获取俱乐部当前排名和数据
     */
    public function getCurrentClubRank($club_id, array $params){
        $paomeId = $params['id'];
        //$roundId = isset($params['status']) ? (int)$params['status'] : 1;
        $roundId = $this->base->load('paome/paomeHall')->getCurrentRound(); 
        $data = array('club_mileage'=>'','club_mileage_rank'=>'','club_speed'=>'','club_speed_rank'=>'','club_supporters'=>'','club_supporters_rank'=>'');
        //跑量榜key
        $rankClubKeyMile = 'rankClub-mileage-'.$paomeId.'-'.$roundId;
        //配速key
        $rankClubKeySpeed = 'rankClub-speed-'.$paomeId.'-'.$roundId;
        //人气key
        $rankClubKeySupportNum = 'rankCLub-supportNum-'.$paomeId.'-'.$roundId;
        if($this->redis->zCard($rankClubKeyMile)) {
            //跑量
            $data['club_mileage'] = $this->redis->zScore($rankClubKeyMile,$club_id);
            $data['club_mileage_rank'] = ($this->redis->zRevRank($rankClubKeyMile,$club_id) !==false) ? ($this->redis->zRevRank($rankClubKeyMile,$club_id)+1) :'';
        }
        if($this->redis->zCard($rankClubKeySpeed)) {
            //配速
            $data['club_speed'] = $this->redis->zScore($rankClubKeySpeed,$club_id);
            $data['club_speed'] = $data['club_speed'] ? common::sec3format($data['club_speed']) : 0;
            $data['club_speed_rank'] = ($this->redis->zRevRank($rankClubKeySpeed,$club_id) !==false) ? ($this->redis->zRevRank($rankClubKeySpeed,$club_id)+1) :'';
        }
        if($this->redis->zCard($rankClubKeySupportNum)) {
            //人气
            $data['club_supporters'] = $this->redis->zScore($rankClubKeySupportNum,$club_id);
            $data['club_supporters_rank'] = ($this->redis->zRevRank($rankClubKeySupportNum,$club_id) !==false) ? ($this->redis->zRevRank($rankClubKeySupportNum,$club_id)+1) :'';
        }         
        return $data;
    }

    /*
     * 个人中心--争霸赛期间战队数据
     */
    public function getClubRankInZb($club_id, array $params){
        $paomeId = $params['id'];
        $round = $this->base->load('paome/paomeHall')->getCurrentRound(); 
        $clubData = array();
        $date = date('Ymd');
        //里程
        $clubData['club_mileage_rank'] = $this->base->load('paome/rank')->getObjectDayRank($club_id, $paomeId, $round, $date, 1);   //排名
        $clubData['club_mileage'] = $this->base->load('paome/rank')->getObjectDayRankValue($club_id, $paomeId, $round, $date, 1);   //数据

        //配速
        $clubData['club_speed_rank'] = $this->base->load('paome/rank')->getObjectDayRank($club_id, $paomeId, $round, $date, 5);   //排名
        $clubData['club_speed'] = $this->base->load('paome/rank')->getObjectDayRankValue($club_id, $paomeId, $round, $date, 5);   //数据

        //人气
        $clubData['club_supporters_rank'] = $this->base->load('paome/rank')->getObjectDayRank($club_id, $paomeId, $round, $date, 10);   //排名
        $clubData['club_supporters'] = $this->base->load('paome/rank')->getObjectDayRankValue($club_id, $paomeId, $round, $date, 10);   //数据
        return $clubData;
    }

    /*
     * 个人中心--获取个人全员跑量榜数据和排名
     */
    public function getCurrentUserRank($uid, array $params){
        $paomeId = $params['id'];
        //$roundId = isset($params['status']) ? (int)$params['status'] : 1;
        $roundId = $this->base->load('paome/paomeHall')->getCurrentRound();
        $data = array();
        //全员跑量榜key
        $rankUserKeyMile = 'rankUser-mileage-'.$paomeId.'-'.$roundId;
        if($this->redis->zCard($rankUserKeyMile)) {
            //获取数据和排名
            $data['user_mileage'] = $this->redis->zScore($rankUserKeyMile,$uid);
            $data['user_mileage_rank'] = ($this->redis->zRevRank($rankUserKeyMile,$uid) !==false) ? ($this->redis->zRevRank($rankUserKeyMile,$uid)+1) :'';
        }       
        return $data;
    }

    /*
     * 个人中心--获取需要排名的全员跑量用户总数
     */
    public function getUserCount(array $params){
        /*$paomeId = $params['id'];
        $roundId = isset($params['status']) ? (int)$params['status'] : 1;
        $userCount = 0;
        $list = array();
        //全员跑量榜key
        $rankUserKeyMile = 'rankUser-mileage-'.$paomeId.'-'.$roundId;
        if($this->redis->zCard($rankUserKeyMile)) {
            $list = $this->redis->zRevRange($rankUserKeyMile,0,-1);
        } 
        if(!empty($list)){
            $userCount = count($list);
        }*/
        $season = $this->base->load('paome/paomeHall')->getCurrentSeason();
        $data = array();
        $userCount = 0;
        if(!empty($season)){
            $seasonId = $season['id'];
            $round = $this->base->load('paome/paomeHall')->getCurrentRound();
            $clubStatus = common::$clubStatusRound; 
            if(!empty($round)){
                foreach ($clubStatus as $k => $v) {
                    if($round == $k){
                        $clubStatus = implode(',', $v);
                    }
                }
                $sql = "SELECT r.id FROM r_pm_users_status s LEFT JOIN r_pm_club r ON r.id = s.club_id WHERE r. STATUS = 0 AND s.contest_id = {$seasonId} AND s.type in ({$clubStatus})";
                $data = $this->paomeDb->getAll($sql);
            }    
        }      
        if($data){
            $club_id = array();
            foreach ($data as &$v) {
                $club_id[] = $v['id'];
            }
            $club_id = implode(',', $club_id);
            $sqlCount = "select count(1) from r_pm_club_users where status = 0 and club_id in ({$club_id})";
            $userCount = $this->paomeDb->getOne($sqlCount);
        } 
        return $userCount;
    }

    /*
     * 个人中心--获取需要排名的俱乐部总数
     */
    public function getClubCount(array $params){
        /*$paomeId = $params['id'];
        $roundId = isset($params['status']) ? (int)$params['status'] : 1;
        $clubCount = 0;
        $list = array();
        //跑量榜key
        $rankClubKeyMile = 'rankClub-mileage-'.$paomeId.'-'.$roundId;
        if($this->redis->zCard($rankClubKeyMile)) {
            $list = $this->redis->zRevRange($rankClubKeyMile,0,-1);
        } 
        if(!empty($list)){
            $clubCount = count($list);
        }*/
        $season = $this->base->load('paome/paomeHall')->getCurrentSeason();
        $clubCount = 0;
        if(!empty($season)){
            $seasonId = $season['id'];
            $round = $this->base->load('paome/paomeHall')->getCurrentRound();
            if(!empty($round)){
                $clubStatus = common::$clubStatusRound; 
                foreach ($clubStatus as $k => $v) {
                    if($round == $k){
                        $clubStatus = implode(',', $v);
                    }
                }
                $sql = "SELECT count(1) FROM r_pm_club_status s LEFT JOIN r_pm_club r ON r.id = s.club_id WHERE r. STATUS = 0 AND s.contest_id = {$seasonId} AND s.type in ({$clubStatus}) AND (s. STATUS = 15 OR s. STATUS = 20)";
                $clubCount = $this->paomeDb->getOne($sql);
            }
        }       
        return $clubCount;
    }

    /*
     * 个人中心--赛季记录:根据轮次获取用户数据
     */
    public function getDataByRound($uid, $round){
        $season = $this->base->load('paome/paomeHall')->getCurrentSeason();
        $data = array();
        $data['clubName'] = '';
        $data['userMileageRank'] = '';
        if(!empty($season)){
            $seasonId = $season['id'];       
            if(!empty($round)){
                $sql = "SELECT * FROM r_pm_users_rounds r WHERE uid = {$uid} AND r.type = {$round} AND r.contest_id = {$seasonId} ORDER BY r.date DESC";
                $data = $this->paomeDb->getRow($sql);
                if($data){
                    $data['clubName'] = $this->getDataUserClub($data['club_id']);
                    $data['speed'] = common::sec3format($data['speed']);
                    //全员跑量榜key
                    $rankUserKeyMile = 'rankUser-mileage-'.$seasonId.'-'.$round;
                    if($this->redis->zCard($rankUserKeyMile)) {
                        //排名
                        $data['userMileageRank'] = ($this->redis->zRevRank($rankUserKeyMile,$uid) !==false) ? ($this->redis->zRevRank($rankUserKeyMile,$uid)+1) :'--';
                    }
                }
            } 
        }             
        return $data;
    }

    /*
     * 个人中心--赛季记录:获取用户所在俱乐部
     */
    public function getDataUserClub($clubId){
        $sql = "SELECT title FROM r_pm_club r WHERE id = {$clubId}";
        return $this->paomeDb->getOne($sql);
    }

    /*
     * 个人中心--获取该用户所属俱乐部当前状态
     */
    public function getClubStatus($seasonId, $clubId){     
        $sql = "SELECT * FROM r_pm_club_status r WHERE contest_id = {$seasonId} AND club_id = {$clubId}";
        $data = $this->paomeDb->getRow($sql);                     
        return $data;
    }

    /*
     * 公告--当天给俱乐部贡献最大数据(大于0)
     */
    public function getMaxDataClub($clubId, $date, $order, $sort = 'desc'){     
        $sql = "SELECT * FROM r_pm_users_rounds WHERE uid in (SELECT uid FROM r_pm_club_users WHERE club_id = {$clubId} AND status = 0) AND date = \"{$date}\"";
        if(!empty($order)){
            $sql .= " order by {$order} {$sort}";
        }
        if($order == 'speed'){
            $sql = "SELECT * FROM r_pm_users_rounds WHERE uid in (SELECT uid FROM r_pm_club_users WHERE club_id = {$clubId} AND status = 0) and speed > 0 AND date = \"{$date}\" order by speed asc";
        }
        $data = $this->paomeDb->getRow($sql); 
        if($data){
            $data['nickname'] = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $data['uid'], 'nickname');
            $data['speed'] = common::sec3format($data['speed']);
        }                    
        return $data;
    }

    /*
     * 分享模块--获取用户的人气数据
     */
    public function getUserPopularity($uid){     
        $season = $this->base->load('paome/paomeHall')->getCurrentSeason();
        $data = array();
        if($season){
            $round = $this->base->load('paome/paomeHall')->getCurrentRound(); 
            $sql = "SELECT * FROM (SELECT @rownum:=@rownum+1 AS rownum,a.uid,a.support_num,(SELECT count(1) FROM r_pm_users_rounds WHERE contest_id = {$season['id']} AND type = {$round}) total_count FROM r_pm_users_rounds a,(SELECT @rownum:=0) b WHERE a.contest_id = {$season['id']} AND a.type = {$round} ORDER BY a.support_num desc) c WHERE c.uid={$uid}";
            $data = $this->paomeDb->getRow($sql);
            //获取第一名的人气
            $sql2 = "select support_num from r_pm_users_rounds WHERE contest_id = {$season['id']} AND type = {$round} order by support_num desc";
            $first = $this->paomeDb->getOne($sql2);
        }
        if($data){
            $data['nickname'] = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $uid, 'nickname');
            $data['header'] = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $uid, 'header');
            $data['rank'] = $data['rownum'] ."/". $data['total_count'];
            !empty($first) && $data['diffLight'] = $first - $data['support_num'];
        }               
        return $data;
    }

    /*
     * 分享模块--获取用户当天点赞次数(微信中)
     */
    public function getLightTimes($openId, $uid){    
        $date = date('Ymd'); 
        $sql = "SELECT light_times FROM r_pm_supporters WHERE type = 2 and is_share = 1 and date = \"{$date}\" and open_id = \"{$openId}\" and target_uid = {$uid}";
        
        return $this->paomeDb->getOne($sql);
    }

    /*
     * 分享模块--获取用户当天点赞次数(app内)
     */
    public function getLightTimesInApp($selfUid, $uid){    
        $date = date('Ymd'); 
        $sql = "SELECT light_times FROM r_pm_supporters WHERE type = 2 and is_share = 1 and date = \"{$date}\" and uid = {$selfUid} and target_uid = {$uid}";
        
        return $this->paomeDb->getOne($sql);
    }

    /*
     * 是否有证书
     */
    public function isCertificate($paomeId,$clubId){    
        $sql = "SELECT id FROM r_pm_certificate WHERE contest_id = {$paomeId} and club_id = {$clubId}";
        $data = $this->paomeDb->getOne($sql);
        return $data ? true : false;
    }

    /*
     * 支持者列表
     */
    public function supportList($target_uid, $type, $is_share = null){    
        $season = $this->base->load('paome/paomeHall')->getCurrentSeason();
        $data = array();
        if(!empty($season)){
            $seasonId = $season['id'];
            $round = $this->base->load('paome/paomeHall')->getCurrentRound();
            $type == 1 && $column = "*,sum(energy) total_energy";
            $type == 2 && $column = "*,sum(light) total_light";
            $sql = "SELECT {$column} FROM r_pm_supporters WHERE contest_id = {$seasonId} and target_uid = {$target_uid} and type = {$type}";
            if($is_share != null){
                $sql .= " and is_share = {$is_share}";
            }
            $sql .= " GROUP BY uid, open_id";
            $type == 1 && $sql .= " order by total_energy desc";
            $type == 2 && $sql .= " order by total_light desc";
            $sql .= " limit 10";
            $data = $this->paomeDb->getAll($sql);
        }
        return $data;
    }

    /*
     * 查询某天用户的单次最远距离
     */
    public function maxMileageByDay($uid, $date){    
        $timeB = strtotime($date);
        $timeE = $timeB + 86400;
        $sql = "select new_mileage from r_pm_club_users_did where uid = {$uid} and create_time >= {$timeB} and create_time < {$timeE} order by new_mileage desc limit 1";
        $maxMileage = $this->paomeDb->getOne($sql);
        return $maxMileage ? $maxMileage : 0;
    }
}